package mysql

import (
	"database/sql"
	"github.com/mitchellh/mapstructure"
	"time"
)

func scanToStruct(rows *sql.Rows, to interface{}) error {
	cols, _ := rows.Columns()

	columns := make([]interface{}, len(cols))
	for i := 0; i < len(cols); i++ {
		var val interface{}
		columns[i] = &val
	}

	if err := rows.Scan(columns...); err != nil {
		return err
	}

	m := make(map[string]interface{})
	for i, colName := range cols {
		m[colName] = *columns[i].(*interface{})
		//把数据库中time类型转为时间戳
		strValue, ok := m[colName].(time.Time)
		if ok {
			m[colName] = strValue.Unix()
		}
		strVal, ok := m[colName].([]uint8)
		if ok {
			m[colName] = string(strVal)
		}
	}

	config := &mapstructure.DecoderConfig{
		Result:           to,
		TagName:          "bson",
		WeaklyTypedInput: true,
	}
	decoder, err := mapstructure.NewDecoder(config)
	if err != nil {
		return err
	}

	if err := decoder.Decode(m); err != nil {
		return err
	}

	return nil
}
